package org.apache.ibatis.myplugin;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;
import java.util.Properties;

/**
 * 统计sql执行时间插件
 *
 */
@Intercepts({
  @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
  @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
  @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
@Slf4j
public class SqlCosTimeInterceptor implements Interceptor {
  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    Object target = invocation.getTarget();

    if (target instanceof StatementHandler) {
      StatementHandler statementHandler = (StatementHandler) target;
      long start = System.currentTimeMillis();
      Object result = invocation.proceed();
      long s = System.currentTimeMillis() - start;
      String sql = statementHandler.getBoundSql().getSql();
      String p = statementHandler.getParameterHandler().getParameterObject().toString();

      // TODO 判断sql执行时间超过 指定毫秒数 异步入库或者发送给监控系统

      System.out.println("sql语句【 " + sql + "】,参数" + p + ",执行耗时: 【" + s + "】 毫秒。");
      return result;
    }else{
      return null;
    }
  }

  @Override
  public Object plugin(Object target) {
    return Interceptor.super.plugin(target);
  }

  @Override
  public void setProperties(Properties properties) {
    Interceptor.super.setProperties(properties);
  }
}
